﻿<cfscript>
/** 
* Bencode Advicer
* 
* @hint "Bencode Advicer" 
*/ 

component 
	displayname="public.service.util.bencodeAdvice" 
	output=false 
	accessors=false 
	{
	
	/* PROPERTIES */
	property name="TorrentMeta" hint="com.fayea.torrent.MetaInfo";
	
	/**
	* @hint "初始化对象"
	*/
	public public.service.util.bencodeAdvice function init() output=false {
		return this;
	}
	
	/**
	* @hint "解析 Torrent 种子文件"
	* 
	* @filePath "种子文件物理路径"
	*/
	public void function parseTorrent( required string filePath ) output=false {
		
		var inputStream = createObject("java", "java.io.FileInputStream").init( arguments.filePath );
		var metaInfo = createObject("java", "com.fayea.torrent.MetaInfo").init( inputStream );
		
		setTorrentMeta( metaInfo );
		
		inputStream.close();
	}
	
	/**
	* @hint "保存种子文件到指定位置"
	* 
	* @filePath "种子文件物理路径"
	*/
	public void function saveTorrent( required string filePath ) output=false {
		
		var ouputStream = createObject("java", "java.io.FileOutputStream").init( arguments.filePath, true );
		
		ouputStream.write( getTorrentMeta().getTorrentData() );
		
		ouputStream.close();
	}
	
	/**
	* @hint "更新AnnounceURL地址"
	* 
	* @announceURL "BT 协议通知地址"
	*/
	public void function setTorrentAnnounceURL( required string announceURL ) output=false {
		
		var metaInfo = getTorrentMeta();
		setTorrentMeta( metaInfo.reannounce( arguments.announceURL ) );
		
	}
	
	/**
	* @hint "获取AnnounceURL地址"
	*/
	public string function getTorrentAnnounceURL() output=false {
		return getTorrentMeta().getAnnounce();
	}
	
	/**
	* @hint "种子HASH值"
	*/
	public string function getTorrentHash() output=false {
		
		var utils = createObject("java", "com.fayea.torrent.Utils");
		
		return utils.byteArrayToByteString( getTorrentMeta().getInfoHash() );
	}
	
	/**
	* @hint "种子文件大小"
	*/
	public numeric function getTorrentTotalLength() output=false {
		return getTorrentMeta().getTotalLength();
	}
	
	/**
	* @hint "种子内容文件列表"
	*/
	public array function getTorrentFile() output=false {
		
		var fileList = [];
		var mutifile = getTorrentMeta().getFiles();
		var mutilength = getTorrentMeta().getLengths();

		/* Mutifles */
		if ( isDefined("mutifile") ) {
			for ( var i=1; i lte arrayLen(mutifile); i++ ) {
				arrayAppend( fileList, [ arrayToList(mutifile[i], "/"), mutilength[i] ] );
			}
		}
		else {
			arrayAppend( fileList, [ getTorrentMeta().getName(), getTorrentMeta().getTotalLength()] );
		}

		return fileList;
	} 

}

</cfscript>